package spring.logger;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.test.context.transaction.AfterTransaction;

@Aspect
public class TestLogger {
	private Logger logger=Logger.getLogger(TestLogger.class);
	
	//<aop:pointcut id="pointcut()" />
	@Pointcut("execution(public * spring.service..*(..))")
	public void pointcut(){}//定义一个共用的切点信息
	
	@Before("pointcut()")
	public void beforeLogger(JoinPoint jp){
		logger.info("开始执行");
		System.out.println("目标对象:"+jp.getTarget());
		System.out.println("方法名:"+jp.getSignature().getName());
		System.out.println("方法参数:"+jp.getArgs()[0]);
	}
	
	@AfterReturning(pointcut="execution(public * spring.service..*(..))",
			returning="result")
	public void afterReturningLogger(JoinPoint jp,Object result){
		logger.info("执行完毕");
		System.out.println("获得返回结果:"+result.toString());
	}
	
	@Around("execution(public * spring.service..*(..))")
	public Object around(ProceedingJoinPoint jp){
		logger.info("环绕增强开始执行方法");
		boolean canExec;
		canExec = false;
		try {
			String input=(String) jp.getArgs()[0];
			if("T01".equals(input)){
				canExec=true;
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			//e1.printStackTrace();
		}
		Object result=null;
		try {
			if(canExec){
				result="加工后的结果:"+jp.proceed();
			}else{
				result="入参不符合要求,请重新输入";
			}
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		logger.info("环绕增强方法执行完毕");
		return result;
	}
	
	@AfterThrowing(pointcut="execution(public * spring.service..*(..))",throwing="e")
	public void afterThrowing(JoinPoint jp,Exception e){
		logger.error("方法执行异常:"+e);
		
	}
	
	@After("execution(public * spring.service..*(..))")
	public void after(JoinPoint jp){
		logger.info("总是会执行的通知");
	}
}
